package com.example.book.transactiontest;

import com.example.book.dao.TUserMapper;
import com.example.book.domain.TUser;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

@Component
public class CommonThread {
    @Resource
    private TUserMapper mapper;

    @Resource
    PlatformTransactionManager platformTransactionManager;

    @Resource
    TransactionTemplate transactionTemplate;

    @Transactional
    public void doTask1() {
//        doTask2In();

        //此处方法3上面的注解失效了！！！！
        new Thread(() -> {
            doTask3Out();
        }).start();
    }


    public void doTask2() {
        doTask2In();
    }

    @Transactional
    private void doTask2In() {

        TUser user = new TUser();
        user.setName("yy");
        mapper.insert(user);

        throw new IllegalArgumentException("FFFFF");
    }


    public void doTask3() {
        //no transaction ???
        doTask3Out();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void doTask3Out() {
        //手动开事务
//        TransactionStatus transaction = platformTransactionManager.getTransaction(TransactionDefinition.ISOLATION_REPEATABLE_READ);
//        platformTransactionManager.commit(transaction);

//        transactionTemplate.execute() //此方法内部也是manager.getTransaction开始事务
        TUser user = new TUser();
        user.setName("xx");
        mapper.insert(user);

        throw new IllegalArgumentException("FFFFF");
    }
}
